/*
 * @Author: yangni 920556271@qq.com
 * @Date: 2023-08-28 15:10:58
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-04-10 09:57:24
 * @FilePath: /yt-devops/lib/pages/devices/device_tab/device_detail/pcs_detail/pcs_detail_controller.dart
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import 'dart:async';

import 'package:get/get.dart';
import 'package:yt_devops/model/device_model.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/base_detail_controller/base_detail_controller.dart';
import 'package:yt_devops/pages/devices/device_tab/utils/device_func_util.dart';

import 'package:yt_devops/utils/socket/use_subscribe.dart';

import 'pcs_detail_model.dart';

class PcsDetailController extends BaseDetailController {
  final PcsDetailModel model = PcsDetailModel();

  late Stream<Map<String, dynamic>> dataStream;

  StreamController<Map<String, dynamic>> streamController = StreamController();

  Map<String, dynamic> datas = {};

  DeviceModel? deviceModel;

  UseSubsribe useSubsribe = UseSubsribe();

  @override
  void onInit() {
    super.onInit();

    var id = Get.arguments['deviceId'];
    connectStatus = Get.arguments['connectStatus'];

    dataStream = useSubsribe.start([id], true).stream.asBroadcastStream();
    // dataStream = useSubscribe([id], true);

    // _channel = IOWebSocketChannel.connect(
    //     '${_getWebSocketHost()}/prod-api/websocket/${getToken()}');

    // _channel.sink.add(jsonEncode({
    //   "data": {
    //     "command": "subscribe",
    //     "params": [
    //       {"device": id}
    //     ]
    //   },
    //   "type": 1
    // }));
    // _channel.stream.listen(
    //   (data) {
    //     if (data is String) {
    //       data = jsonDecode(data);
    //       var res = data['data'];
    //       Map<String, dynamic> obj = {};
    //       if (res is Map && res['keyValues'] != null) {
    //         res['keyValues']?.forEach((item) {
    //           obj.putIfAbsent(item['key'], () => item['value']);
    //         });
    //         datas.addEntries(obj.entries);
    //         streamController.add(datas);
    //       }
    //     }
    //   },
    // );
  }

  initData() async {
    var groups = await DeviceFuncUtils.getFormateByDeviceModel([
      model.runItems,
      model.exchargeItems,
      model.directCurrentItems,
      model.tempItems,
      model.versionItems,
    ], deviceModel?.productId);
    model.runItems = groups[0];
    model.exchargeItems = groups[1];
    model.directCurrentItems = groups[2];
    model.tempItems = groups[3];
    model.versionItems = groups[4];
    update();
  }

  @override
  void onReady() {}

  @override
  void onClose() {
    useSubsribe.closeListen();
  }
}
